/* eslint-disable prettier/prettier */
// import RNFS from 'react-native-fs';
import CryptoJS from 'crypto-js';
import downloadFile  from './DownLoad';
import { store } from '../store/store';
import { Store } from '../enums/constant';
import { WXstate } from '../enums/constant';
interface NewWord {
    dictionary: string;
    wordPath: string;
    wordName: string;
}

interface Chapter {
    newWordList: NewWord[];
    directoryList: string[];
    chapterName: string;
}
interface Unit {
    chapterlist: Chapter[];
    unitname: string;
}

interface Book {
    unitlists: Unit[];
    bookName: string;
}

const location = `${WXstate.DOWNLOAD_LOCATION}`;
const Downloadfromjson = async (unitnames: string): Promise<void> => {
    console.log('dealing with json');
    try {
        // 加载 JSON 文件并自动解析为 JavaScript 对象
        const jsonObject: Book = require('../../android/app/src/main/res/grade_1_1_0.json');
        console.log(jsonObject);
        // 使用 TypeScript 类型守卫来找到匹配的单元
        let targetUnit = jsonObject.unitlists.find(Unit => Unit.unitname === unitnames);
        if (targetUnit) {
            let directoryList = targetUnit.chapterlist[0].directoryList;
            // 确保 map 函数返回一个 Promise 数组
            let action = {type:Store.DOWNLOAD_STORE,
                            isLoadingStatus:'true',
                        };
            store.dispatch(action);
            console.log(store.getState().rootReducer.IsloadingReducer.isLoadingStatus);
            Promise.all(directoryList.map(async (directory: string) => {
                try {
                    let uri = `${location}${encode(directory)}`;
                    console.log(uri + '.zip');
                    await downloadFile(uri + '.zip', encode(directory) + '.zip', (progress) => {
                        console.log(`下载进度: ${progress * 100}%`);
                      });
                } catch (error) {
                    console.error(`Error downloading ${directory}:`, error);
                    // 这里可以添加错误处理逻辑，例如重试下载
                }
                action = {type:Store.DOWNLOAD_STORE,
                    isLoadingStatus:'false',
                };
                store.dispatch(action);
                console.log(store.getState().rootReducer.IsloadingReducer.isLoadingStatus);
            }));
        } else {
            console.log('没有对应的下载资源！');
        }
    } catch (error) {
        console.error('Error processing JSON or finding unit:', error);
    }
};

 
const encode = (datasource:string) => {
    try {
        const key = `${WXstate.KEY_DO}`;
      // DES requires the key to be exactly 8 bytes long
      const desKey = CryptoJS.enc.Utf8.parse(key.substring(0, 8)); // Truncate or use the first 8 characters of the key

      // Convert the datasource to a WordArray
      const data = CryptoJS.enc.Utf8.parse(datasource);

      // DES encryption
      const encrypted = CryptoJS.DES.encrypt(data, desKey, {
        mode: CryptoJS.mode.ECB, // Electronic Codebook mode
        padding: CryptoJS.pad.Pkcs7, // Padding scheme
      });

      // Return Base64 encoded ciphertext
      let st = encrypted.toString().replace(/=+$/, '');
      console.log(st);

      return st.replace(/[^A-Za-z0-9]/g, '_');

    } catch (e) {
      console.error('Encryption error:', e);
      return null;
    }
  };

export default Downloadfromjson;
